package com.cheng.im.gateway.session.dao.impl;

import com.alibaba.fastjson2.JSONObject;
import com.cheng.im.common.constants.RedisConstants;
import com.cheng.im.common.entity.SessionCache;
import com.cheng.im.common.entity.UserCache;
import com.cheng.im.gateway.session.dao.UserCacheDAO;
import org.redisson.api.RMap;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@Service
public class RedissonUserCacheImpl implements UserCacheDAO {

    @Resource
    private RedissonClient redissonClient;
    private static final long CASHE_LONG = 60 * 4;//4小时之后，得重新登录


    @Override
    public void save(UserCache s) {

    }

    @Override
    public UserCache get(String userId, String appId) {
        RMap<String, String> map = redissonClient.getMap(appId + RedisConstants.UserSessionConstants + userId);

        Map<String, SessionCache> sessionCacheMap = new HashMap<>();
        // 获取map中的所有键值对
        Set<Map.Entry<String, String>> entries = map.entrySet();
        for (Map.Entry<String, String> entry : entries) {
            // System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue());
            sessionCacheMap.put(entry.getKey(), JSONObject.parseObject(entry.getValue(), SessionCache.class));
        }


        UserCache userCache = new UserCache(userId, appId);
        userCache.setMap(sessionCacheMap);

        return userCache;
    }

    @Override
    public void addSession(String uid, SessionCache session, String appId) {
        RMap<String, String> map = redissonClient.getMap(appId + RedisConstants.UserSessionConstants + uid);

        map.put(session.getSessionId(), JSONObject.toJSONString(session));
    }

    @Override
    public void removeSession(String uid, String sessionId, String appId) {
        RMap<String, String> map = redissonClient.getMap(appId + RedisConstants.UserSessionConstants + uid);

        map.remove(sessionId);
    }
}
